
package com.anjiplus.template.gaea.business.modules.httpdir.service.impl;

import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.modules.datasetparam.controller.dto.DataSetParamDto;
import com.anjiplus.template.gaea.business.modules.datasetparam.dao.entity.DataSetParam;
import com.anjiplus.template.gaea.business.modules.datasetparam.service.DataSetParamService;
import com.anjiplus.template.gaea.business.modules.datasettransform.controller.dto.DataSetTransformDto;
import com.anjiplus.template.gaea.business.modules.datasettransform.dao.entity.DataSetTransform;
import com.anjiplus.template.gaea.business.modules.datasettransform.service.DataSetTransformService;
import com.anjiplus.template.gaea.business.modules.httpdir.controller.dto.HttpDirDto;
import com.anjiplus.template.gaea.business.modules.httpdir.dao.HttpDirMapper;
import com.anjiplus.template.gaea.business.modules.httpdir.dao.entity.HttpDir;
import com.anjiplus.template.gaea.business.modules.httpdir.service.HttpDirService;
import com.anjiplus.template.gaea.business.modules.https.controller.dto.HttpDto;
import com.anjiplus.template.gaea.business.modules.https.service.HttpService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author Raod
 * @desc HttpDir 数据集服务实现
 * @date 2021-03-18 12:11:31.150755900
 **/
@Service
//@RequiredArgsConstructor
@Slf4j
public class HttpDirServiceImpl implements HttpDirService {

    @Autowired
    private HttpDirMapper HttpMapper;

    @Autowired
    private DataSetParamService dataSetParamService;

    @Autowired
    private DataSetTransformService dataSetTransformService;

    @Autowired
    private HttpService httpService;



    @Override
    public GaeaBaseMapper<HttpDir> getMapper() {
        return HttpMapper;
    }

    /**
     * 单条详情
     *
     * @param id
     * @return
     */
    @Override
    public HttpDirDto detailSetById(String id) {
        HttpDirDto dto = new HttpDirDto();
        HttpDir result = selectOne(id);
        GaeaBeanUtils.copyAndFormatter(result, dto);
        return getDetailSet(dto);
    }

    @Override
    public List<HttpDirDto> queryAllDirs() {
        List<HttpDir> httpDirs = HttpMapper.selectList(null);
        Map<String, HttpDirDto> parentMap = new HashMap<>();
        List<HttpDirDto> result = new ArrayList<>();

        // 先查询父节点并初始化父节点映射
        for (HttpDir httpDir : httpDirs) {
            HttpDirDto httpDirDto = new HttpDirDto();
            BeanUtils.copyProperties(httpDir, httpDirDto);
            //查询父节点下挂载的http记录
            List<HttpDto> https = httpService.queryByDirId(httpDirDto.getId());
            httpDirDto.setHttps(https);
//            if (httpDir.getParentId().equals("-1")) {
//                result.add(httpDirDto);  // 如果是父节点，直接添加到结果列表
//                parentMap.put(httpDir.getId(), httpDirDto);  // 将父节点放入映射中
//            }
            result.add(httpDirDto);
        }


        /*for (HttpDir httpDir : httpDirs) {
            HttpDirDto httpDirDto = new HttpDirDto();
            BeanUtils.copyProperties(httpDir, httpDirDto);

            if (!httpDir.getParentId().equals("-1")) {
                // 如果是子节点，找到对应的父节点并添加子节点
                HttpDirDto parent = parentMap.get(httpDir.getParentId());
                if (parent != null) {
                    List<HttpDirDto> children = parent.getChildren();
                    if (children == null) {
                        children = new ArrayList<>();
                        parent.setChildren(children);  // 初始化父节点的子节点列表
                    }
                    //查询父节点下挂载的http记录
                    List<Http> https = httpService.queryByDirId(httpDirDto.getId());
                    httpDirDto.setHttps(https);
                    children.add(httpDirDto);  // 添加当前子节点
                }
            }
        }*/

        return result;
    }

    /**
     * 单条详情
     *
     * @param setCode
     * @return
     */
    @Override
    public HttpDirDto detailSet(String setCode) {
        HttpDirDto dto = new HttpDirDto();
        HttpDir result = selectOne("set_code", setCode);
        GaeaBeanUtils.copyAndFormatter(result, dto);
        return getDetailSet(dto);
    }

    public HttpDirDto getDetailSet(HttpDirDto dto) {
        //查询参数

        return dto;
    }


    /**
     * 新增数据集、添加查询参数、数据转换
     *
     * @param dto
     */
    @Override
    @Transactional
    public HttpDirDto insertSet(HttpDirDto dto) {
        String username = UserContentHolder.getContext().getUsername();
        dto.setCreateBy(username);
        dto.setCreateTime(new Date());

        HttpDir dataSet = new HttpDir();
        BeanUtils.copyProperties(dto, dataSet);
        insert(dataSet);
        return dto;
    }

    /**
     * 更新数据集、添加查询参数、数据转换
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSet(HttpDirDto dto) {
        if (StringUtils.isEmpty(dto.getId())) {
            throw new RuntimeException("id为空修改失败!");
        }
        String username = UserContentHolder.getContext().getUsername();
        dto.setUpdateBy(username);
        dto.setUpdateTime(new Date());
        //1.更新数据集
        HttpDir dataSet = new HttpDir();
        BeanUtils.copyProperties(dto, dataSet);
        update(dataSet);
    }


    /**
     * 删除数据集、添加查询参数、数据转换
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSet(String id) {
        HttpDir dataSet = selectOne(id);
        //1.删除数据集
        deleteById(id);

    }

    public void copy(HttpDirDto dto) {
        if (null == dto.getId()) {
            throw BusinessExceptionBuilder.build(ResponseCode.NOT_NULL, "id");
        }
        HttpDir dataSet = selectOne(dto.getId());
        HttpDir dateSetCopy = copyDataSet(dataSet);
        insert(dateSetCopy);
    }

    public void dataSetParamBatch(List<DataSetParamDto> dataSetParamDtoList, String setCode) {
        dataSetParamService.delete(
                new QueryWrapper<DataSetParam>()
                        .lambda()
                        .eq(DataSetParam::getSetCode, setCode)
        );
        if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) {
            return;
        }
//        List<DataSetParam> dataSetParamList = new ArrayList<>();
        dataSetParamDtoList.forEach(dataSetParamDto -> {
            DataSetParam dataSetParam = new DataSetParam();
            BeanUtils.copyProperties(dataSetParamDto, dataSetParam);
            dataSetParam.setSetCode(setCode);
            //不采用批量
            dataSetParamService.insert(dataSetParam);
//            dataSetParamList.add(dataSetParam);
        });
//        dataSetParamService.insertBatch(dataSetParamList);

    }

    public void dataSetTransformBatch(List<DataSetTransformDto> dataSetTransformDtoList, String setCode) {
        dataSetTransformService.delete(
                new QueryWrapper<DataSetTransform>()
                        .lambda()
                        .eq(DataSetTransform::getSetCode, setCode)
        );
        if (null == dataSetTransformDtoList || dataSetTransformDtoList.size() <= 0) {
            return;
        }
//        List<DataSetTransform> dataSetTransformList = new ArrayList<>();
        for (int i = 0; i < dataSetTransformDtoList.size(); i++) {
            DataSetTransform dataSetTransform = new DataSetTransform();
            BeanUtils.copyProperties(dataSetTransformDtoList.get(i), dataSetTransform);
            dataSetTransform.setOrderNum(i + 1);
            dataSetTransform.setSetCode(setCode);
            //不采用批量
            dataSetTransformService.insert(dataSetTransform);
//            dataSetTransformList.add(dataSetTransform);
        }
//        dataSetTransformService.insertBatch(dataSetTransformList);
    }

    /**
     * dataSetParamDtoList转map
     *
     * @param dataSetParamDtoList
     * @return
     */
    public Map<String, Object> setContextData(List<DataSetParamDto> dataSetParamDtoList) {
        Map<String, Object> map = new HashMap<>();
        if (null != dataSetParamDtoList && dataSetParamDtoList.size() > 0) {
            dataSetParamDtoList.forEach(dataSetParamDto -> map.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem()));
        }
        return map;
    }

    private HttpDir copyDataSet(HttpDir dataSet) {
        //复制主表数据
        HttpDir copyDataSet = new HttpDir();
        GaeaBeanUtils.copyAndFormatter(dataSet, copyDataSet);
        copyDataSet.setId(null);
        return copyDataSet;
    }

}
